<?php
declare (strict_types=1);

namespace app\controller;

use app\BaseController;
use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;

class PubSub extends BaseController
{
    public function send()
    {
        // 交换机名
        $exchange = 'logs';

        // 建立连接
        $connection = new AMQPStreamConnection('127.0.0.1', '5672', 'guest', 'guest', '/');
        // 获取信道
        $channel = $connection->channel();
        // 声明交换机
        $channel->exchange_declare($exchange, 'fanout', false, false, false);

        for ($i = 0; $i < 5; ++$i) {
            sleep(1); // 休眠1s
            // 消息内容
            $messageBody = 'heelo,zq now time:' . date('h:i:s');
            // 将我们需要的消息标记为持久化
            $message = new AMQPMessage($messageBody, [
                'content_type' => 'text/plain',
                'delivery_mode' => AMQPMessage::DELIVERY_MODE_PERSISTENT
            ]);

            // 发送消息
            $channel->basic_publish($message, $exchange);
            echo 'send message:' . $i . "\n";
        }

        // 关闭信道
        $channel->close();
        // 关闭连接
        $connection->close();
        return 'send success';
    }
}
